package web

import (
	"errors"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"io"
	"mts/user_srv/internal/domain"
	"mts/user_srv/internal/service"
	"mts/user_srv/internal/web/response"
	"net/http"
)

type CodeHandler struct {
	svc service.CodeService
}

func NewCodeHandler(svc service.CodeService) *CodeHandler {
	return &CodeHandler{svc: svc}
}

func (handler CodeHandler) RegisterRoutes(group *gin.RouterGroup) {
	zap.S().Info("配置验证码相关 URL")

	// 路由分组
	codeGroup := group.Group("/code")
	{
		codeGroup.POST("/send_sms", handler.SendSMS)
		codeGroup.GET("/captcha", GetCaptcha)
	}
}

func (handler CodeHandler) SendSMS(ctx *gin.Context) {
	sendSmsForm := domain.SendSmsForm{}
	if err := ctx.ShouldBind(&sendSmsForm); err != nil {
		if errors.Is(err, io.EOF) {
			ctx.JSON(http.StatusBadRequest, gin.H{"msg": "请求体为空"})
			return
		}
		zap.S().Errorw("表单绑定失败", "err", err)
		response.HandlerValidatorError(ctx, err)
		return
	}
	err := handler.svc.SendSMS(sendSmsForm)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"msg": "发送失败"})
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg": "发送成功",
	})
}
